﻿//234. 回文链表
//给你一个单链表的头节点 head ，请你判断该链表是否为回文链表。
//如果是，返回 true ；否则，返回 false 。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

class Solution {
public:
    //链表反转
    ListNode* reserve(ListNode* list)
    {
        ListNode* prev = nullptr;
        ListNode* curr = list;
        ListNode* next = nullptr;

        while (curr)
        {
            next = curr->next;
            curr->next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }

    bool isPalindrome(ListNode* head)
    {
        if (!head)
        {
            return true;
        }
        ListNode* slow = head;
        ListNode* fast = head;
        while (fast->next && fast->next->next)
        {
            fast = fast->next->next;
            slow = slow->next;
        }
        //反转后半段链表

        ListNode* headnew = reserve(slow->next);
        slow->next = nullptr;
        ListNode* p1 = head;
        ListNode* p2 = headnew;
        bool ans = true;
        while (p2 && ans)
        {
            if (p2->val != p1->val)
                ans = false;
            p2 = p2->next;
            p1 = p1->next;

        }
        slow->next = reserve(headnew);
        return ans;
    }
};